package com.kingzoon.seckill.base.listener;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import ch.qos.logback.classic.Logger;

import com.kingzoon.seckill.base.Constants;
import com.kingzoon.seckill.base.redis.RedisClientTemplate;

/**
 * 会话监听器
 * @author xiemin
 * @date 2016-11-2下午4:12:49
 * @version 1.0
 */
public class SessionListener implements HttpSessionListener {
	
	@Autowired
	private RedisClientTemplate rct;
	
	protected Logger log = (Logger) LoggerFactory.getLogger(SessionListener.class);

	public void sessionCreated(HttpSessionEvent event) {
		HttpSession session = event.getSession();
		session.setAttribute(Constants.WEBTHEME, "default");
		log.info("创建了一个Session连接:[" + session.getId() + "]");
		//TODO 统计在线人数
		//setAllUserNumber(1);
	}

	public void sessionDestroyed(HttpSessionEvent event) {
		HttpSession session = event.getSession();
/*		if (getAllUserNumber() > 0) {
			log.info("销毁了一个Session连接:[" + session.getId() + "]");
		}*/
		session.removeAttribute(Constants.CURRENT_USER);
		//TODO 销毁会话
		//sessionService.deleteBySessionId(session.getId());
		//setAllUserNumber(-1);
	}
	
	private void setAllUserNumber(int n) {
		Long number = getAllUserNumber() + n;
		if (number >= 0) {
			log.info("用户数：" + number);
			rct.setrange(Constants.ALLUSER_NUMBER, 60 * 60 * 24, String.valueOf(number));
		}
	}
	
	/** 获取在线用户数量 */
	public Long getAllUserNumber() {
		String v = rct.get(Constants.ALLUSER_NUMBER);
		if (v != null) {
			return Long.valueOf(v);
		}
		return 0L;
	}

}
